package com.habdqn.studentmanager.controller;

import java.io.UnsupportedEncodingException;
import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageInfo;
import com.github.xiaofan1519.verify.core.Verify;
import com.github.xiaofan1519.verify.exception.VerifyException;
import com.habdqn.studentmanager.bean.Dictionary;
import com.habdqn.studentmanager.bean.Teacher;
import com.habdqn.studentmanager.bean.ajax.RowsResponse;
import com.habdqn.studentmanager.constant.Constant;
import com.habdqn.studentmanager.constant.DictType;
import com.habdqn.studentmanager.constant.ErrorCode;
import com.habdqn.studentmanager.constant.FieldDefine;
import com.habdqn.studentmanager.exception.StudentException;
import com.habdqn.studentmanager.service.SystemService;
import com.habdqn.studentmanager.service.TeacherService;

/**
 * @author Administrator 教师控制器类 2017年5月17日
 * 
 */
@Controller
@RequestMapping("/teacher")
public class TeacherController extends BaseController {

    private static Logger logger = Logger.getLogger(TeacherController.class);

    @Resource
    private TeacherService teacherService;

    @Resource
    private SystemService systemService;

    /**
     * 新增页面的准备工作
     * 
     * @param attr
     * @return
     */
    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String toAddTeacher(Model model) {

        List<Dictionary> teacherTypes = null;

        try {
            teacherTypes = systemService.findDictList(Dictionary.make(DictType.TeacherType, null, null));
        }
        catch (StudentException e) {
            logger.error("system error", e);
            model.addAttribute(Constant.ERROR_MSG, "获取教师类型失败");
            return Constant.ERROR_PAGE;
        }

        model.addAttribute("types", teacherTypes);
        return "teacher/add";
    }

    /**
     * 新增教师
     * 
     * @param bean
     * @return
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String addTeacher(Teacher bean, Model model) {

        try {
            Verify.verifyNull(bean);

            Verify.verifyLen(bean.getAccount(), FieldDefine.MIN_PASSWD_LENTH, FieldDefine.MAX_PASSWD_LENTH);
            Verify.verifyLen(bean.getName(), FieldDefine.MIN_NAME_LENGTH, FieldDefine.MAX_NAME_LENGTH);

            Verify.verifyLenAllowEmpty(bean.getTel(), FieldDefine.MIN_TEL_LENTH, FieldDefine.MAX_TEL_LENTH);

            Verify.verifyNull(bean.getType());
            Verify.verifyNull(bean.getType().getValue());
            Verify.verifyLenAllowEmpty(bean.getRemarks(), FieldDefine.MIN_REMARKS_LENTH, FieldDefine.MAX_REMARKS_LENTH);

            Verify.verifyEmailAllowEmpty(bean.getEmail());

            Verify.verifyLenAllowEmpty(bean.getRemarks(), FieldDefine.MIN_REMARKS_LENTH, FieldDefine.MAX_REMARKS_LENTH);
        }
        catch (VerifyException e) {
            logger.debug("参数校验失败", e);
            model.addAttribute(Constant.ERROR_MSG, "参数非法");
            return Constant.ERROR_PAGE;
        }

        try {
            teacherService.add(bean);
        }
        catch (StudentException e) {
            model.addAttribute(Constant.ERROR_MSG, e.getMessage());
            return Constant.ERROR_PAGE;
        }

        return "redirect:/teacher/list";
    }

    /**
     * 展示教师列表
     * 
     * @param bean
     * @param pageNum
     * @param pageSize
     * @param model
     * @return
     */
    @RequestMapping("/list")
    public String list(Teacher bean, @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize, Model model) {

        if (null == pageNum) {
            pageNum = 1;
        }

        if (null == pageSize) {
            pageSize = 10;
        }

        // 查询日志类型
        List<Dictionary> teacherTypes = null;
        PageInfo<Teacher> pageInfo = null;
        try {
            teacherTypes = systemService.findDictList(Dictionary.make(DictType.TeacherType, null, null));
            pageInfo = teacherService.findList(bean, pageNum, pageSize);
        }
        catch (StudentException e) {
            model.addAttribute(Constant.ERROR_MSG, e.getMessage());
            return Constant.ERROR_PAGE;
        }

        Integer typeValue = null;
        if (null != bean && null != bean.getType()) {
            typeValue = bean.getType().getValue();
        }

        String nameValue = null;
        if (null != bean) {
            nameValue = bean.getName();
        }

        model.addAttribute("types", teacherTypes);
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("typeValue", typeValue);
        model.addAttribute("nameValue", nameValue);
        return "teacher/list";
    }

    /**
     * 根据条件，返回json格式的教师列表
     * 
     * @param name
     * @param type
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping(value = "/lists", method = RequestMethod.GET)
    @ResponseBody
    public RowsResponse lists(@RequestParam(required = false) String name, @RequestParam(required = false) Integer type,
            @RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "10") Integer pageSize) {

        if (null == pageNum) {
            pageNum = 1;
        }

        if (null == pageSize) {
            pageSize = 10;
        }

        RowsResponse rsp = new RowsResponse();
        try {
            Teacher bean = new Teacher();
            bean.setName(name);
            bean.setType(Dictionary.make(null, null, type));
            PageInfo<Teacher> pageInfo = teacherService.findList(bean, pageNum, pageSize);
            
            rsp.setTotal(pageInfo.getTotal());
            rsp.setRows(pageInfo.getList());
            return rsp;
        }
        catch (StudentException e) {
            rsp.setErr(ErrorCode.System_Error);
            rsp.setMsg(e.getMessage());
            return rsp;
        }
    }

    @RequestMapping("/info")
    public String info(Integer id, Model model) {

        if (null == id) {
            model.addAttribute(Constant.ERROR_MSG, "参数非法");
            return Constant.ERROR_PAGE;
        }

        Teacher bean = new Teacher();
        bean.setId(id);
        try {
            bean = teacherService.find(bean);
            if (null == bean) {
                model.addAttribute(Constant.ERROR_MSG, "该教师不存在");
                return Constant.ERROR_PAGE;
            }
        }
        catch (StudentException e) {
            model.addAttribute(Constant.ERROR_MSG, e.getMessage());
            return Constant.ERROR_PAGE;
        }

        model.addAttribute("bean", bean);
        return "teacher/info";
    }

    /**
     * 删除教师
     * 
     * @param bean
     * @param model
     * @return
     */
    @RequestMapping("/delete")
    public String delete(Teacher bean, Model model) {

        try {
            Verify.verifyNull(bean);
            Verify.verifyNull(bean.getId());
        }
        catch (VerifyException e) {
            logger.debug("参数非法", e);
            model.addAttribute(Constant.ERROR_MSG, "参数非法");
            return Constant.ERROR_PAGE;
        }

        try {
            teacherService.delete(bean);
        }
        catch (StudentException e) {
            model.addAttribute(Constant.ERROR_MSG, e.getMessage());
            return Constant.ERROR_PAGE;
        }

        return "redirect:/teacher/list";
    }

    /**
     * 跳转至编辑教师页面
     * 
     * @param bean
     * @param model
     * @return
     */
    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String toEdit(Teacher bean, Model model) {
        
        try {
            Verify.verifyNull(bean);
            Verify.verifyNull(bean.getId());
        }
        catch (VerifyException e) {
            logger.error("参数非法", e);
            model.addAttribute(Constant.ERROR_MSG, "参数非法");
            return Constant.ERROR_PAGE;
        }

        List<Dictionary> teacherTypes = null;
        try {
            teacherTypes = systemService.findDictList(Dictionary.make(DictType.TeacherType, null, null));

            bean = teacherService.find(bean);
            if (null == bean) {
                model.addAttribute(Constant.ERROR_MSG, "该教师不存在");
                return Constant.ERROR_PAGE;
            }
            bean.setPassword(null);
        }
        catch (StudentException e) {
            logger.error("system error", e);
            model.addAttribute(Constant.ERROR_MSG, e.getMessage());
            return Constant.ERROR_PAGE;
        }

        model.addAttribute("bean", bean);
        model.addAttribute("types", teacherTypes);
        return "teacher/edit";
    }

    /**
     * 编辑教师
     * 
     * @param bean
     * @param model
     * @return
     * @throws UnsupportedEncodingException
     */
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public String edit(Teacher bean, Model model) {

        try {
            Verify.verifyNull(bean);
            Verify.verifyNull(bean.getId());
            Verify.verifyLen(bean.getName(), FieldDefine.MIN_NAME_LENGTH, FieldDefine.MAX_NAME_LENGTH);

            Verify.verifyLenAllowEmpty(bean.getTel(), FieldDefine.MIN_TEL_LENTH, FieldDefine.MAX_TEL_LENTH);

            Verify.verifyNull(bean.getType());
            Verify.verifyNull(bean.getType().getValue());
            Verify.verifyLenAllowEmpty(bean.getRemarks(), FieldDefine.MIN_REMARKS_LENTH, FieldDefine.MAX_REMARKS_LENTH);

            Verify.verifyEmailAllowEmpty(bean.getEmail());

            Verify.verifyLenAllowEmpty(bean.getRemarks(), FieldDefine.MIN_REMARKS_LENTH, FieldDefine.MAX_REMARKS_LENTH);
        }
        catch (VerifyException e) {
            logger.debug("参数校验失败", e);
            model.addAttribute(Constant.ERROR_MSG, "参数非法");
            return Constant.ERROR_PAGE;
        }

        try {
            bean.setPassword(null);
            teacherService.update(bean);
        }
        catch (StudentException e) {
            logger.error("编辑教师失败", e);
            model.addAttribute(Constant.ERROR_MSG, e.getMessage());
            return Constant.ERROR_PAGE;
        }

        addAttr(model, "msg", "操作成功");
        return "success";
    }
}
